package main

import "flag"
import "fmt"
import "bufio"
import "io"
import "os"
import "time"
import "strconv"
import "algorithms/bubblesort"
import "algorithms/qsort"

//second parameter is default value
var infile *string = flag.String("i","unsorted.dat","file contains values for sort")
var outfile *string = flag.String("o","sorted.dat","file to recevie sorted value")
var algorithm *string = flag.String("a","qsort","sort algorithm")

func readValues(infile string) (values []int, err error) {
	file, err := os.Open(infile)
	if err != nil {
		fmt.Println("failed to open the input file ",infile)
		return
	}
	defer file.Close()
	br := bufio.NewReader(file)
	values = make([]int,0) //最终返回的slice data
	for {
		line, isPrefix, err1 := br.ReadLine()
		if err1 != nil {
			if err1 != io.EOF {
				err = err1
			}
			break;
		}
		if isPrefix {
			fmt.Println("a too long line. seems unexpected.")
			return
		}
		str := string(line) //what's type of line ?
		value, err1 := strconv.Atoi(str)
		if err1 != nil {
			err = err1
			return
		}
		values = append(values,value)
	}
	return
}

func writeValues(values []int, outfile string) error {
	file, err := os.Create(outfile)
	if err != nil {
		fmt.Println("failed to create output file ", outfile)
		return err
	}
	defer file.Close()
	for _, value := range values {
		str := strconv.Itoa(value)
		file.WriteString(str + "\n")
	}
	return nil
}

func main() {
	flag.Parse()
	if infile != nil {
		fmt.Println("infile=",*infile, "outfile=", *outfile,"algorithm=", *algorithm)
	}
	values,err := readValues(*infile)
	if err == nil {
		t1 := time.Now()
		switch *algorithm {
		case "qsort":
			qsort.QuickSort(values) //类似fmt.Println，写上包名
		case "bubblesort":
			bubblesort.BubbleSort(values)
		default:
			fmt.Println("unsupported algorithm")
		}
		t2 := time.Now()
		fmt.Println("sort costs ",t2.Sub(t1))
		writeValues(values,*outfile)
	}else {
		fmt.Println(err)
	}
}